<?php

/*
 * CopyRight  : (C)2012-2099 HaoTeam Inc.
 * Document   : SystemSubscribe.php
 * Created on : 2021-1-30 16:56:49
 * Author     : Tiger <1192851302@qq.com>
 * Description: This is NOT a freeware, use is subject to license terms.
 *              这即使是一个免费软件,使用时也请遵守许可证条款,得到当时人书面许可.
 *              未经书面许可,不得翻版,翻版必究;版权归属 HaoTeam Inc;
 */

namespace haoteam\subscribes;

use think\helper\Str;
use haoteam\service\AdminService;
use app\admin\model\AdminActionLog;
use app\admin\model\AdminConfig;

/**
 * 后台系统事件
 * Class LogsSubscribe
 * Tiger <1192851302@qq.com> 2021-1-30 16:56:49
 */
class SystemSubscribe {

    /**
     * 
     * @param type $event
     */
    public function onHttpRun($event) {
        if (AdminConfig::getOne('system_action_log_open')) {
            /* ! 全局数据变更数据 */
            $GLOBALS['oplogs'] = [];
            /* ! 数据操作SQL语句监听分析 */
            app()->db->listen(function ($sqlstr) {
                [$type] = explode(' ', $sqlstr);
                if (in_array($type, ['INSERT', 'UPDATE', 'DELETE']) && AdminService::instance()->getUserId()) {
                    [$sqlstr] = explode('GROUP BY', explode('ORDER BY', $sqlstr)[0]);
                    if (preg_match('/^INSERT\s+INTO\s+`(.*?)`\s+SET\s+(.*?)\s*$/i', $sqlstr, $matches)) {
                        if (stripos($matches[1] = Str::studly($matches[1]), 'HtAdminActionLog') === false) {
                            $matches[2] = substr(str_replace(['`', '\''], '', $matches[2]), 0, 800);
                            $GLOBALS['oplogs'][] = AdminActionLog::write_bind_data("添加{$matches[1]}数据", $matches[2]);
                        }
                    } elseif (preg_match('/^INSERT\s*INTO\s+`(.*?)`\s+(.*?)\s+VALUES\s+(.*?)\s*$/i', $sqlstr, $matches)) {
                        if (stripos($matches[1] = Str::studly($matches[1]), 'HtAdminActionLog') === false) {
                            $matches[2] = substr(str_replace(['`', '\''], '', $matches[2]), 0, 200);
                            $matches[3] = substr(str_replace(['`', '\''], '', $matches[3]), 0, 600);
                            $GLOBALS['oplogs'][] = AdminActionLog::write_bind_data("添加{$matches[1]}数据", "{$matches[2]} VALUES {$matches[3]}");
                        }
                    } elseif (preg_match('/^UPDATE\s+`(.*?)`\s+SET\s+(.*?)\s+WHERE\s+(.*?)\s*$/i', $sqlstr, $matches)) {
                        if (stripos($matches[1] = Str::studly($matches[1]), 'HtAdminActionLog') === false) {
                            $matches[3] = substr(str_replace(['`', '\''], '', $matches[3]), 0, 150);
                            $matches[2] = substr(str_replace(['`', '\''], '', $matches[2]), 0, 800);
                            $GLOBALS['oplogs'][] = AdminActionLog::write_bind_data("更新{$matches[1]}数据", "{$matches[3]} ," . $matches[2]);
                        }
                    } elseif (preg_match('/^DELETE\s*FROM\s*`(.*?)`\s*WHERE\s*(.*?)\s*$/i', $sqlstr, $matches)) {
                        if (stripos($matches[1] = Str::studly($matches[1]), 'HtAdminActionLog') === false) {
                            $matches[2] = str_replace(['`', '\''], '', $matches[2]);
                            $GLOBALS['oplogs'][] = AdminActionLog::write_bind_data("删除{$matches[1]}数据", "{$matches[2]}");
                        }
                    }
                }
            });
        }
    }

    /**
     * 
     * @param type $event
     */
    public function onHttpEnd($event) {
        if (AdminConfig::getOne('system_action_log_open')) {
            if (is_array($GLOBALS['oplogs']) && count($GLOBALS['oplogs']) > 0) {
                foreach (array_chunk($GLOBALS['oplogs'], 100) as $items) {
                    AdminActionLog::insertAll($items);
                }
                $GLOBALS['oplogs'] = [];
            }
        }
    }

}
